import Taro, { Component } from '@tarojs/taro'
import {
  Swiper,
  SwiperItem,
  Image,
  View,
  Text,
  Input,
} from '@tarojs/components'
import '../../assets/common.scss'
import CommonJs from '../../utils/common'
import Footer from '../index/footer'
import Gwlist from '../index/gwlist'
import './mall.scss'

import cat01 from './images/pcat01.png'
import cat02 from './images/pcat02.png'
import cat03 from './images/pcat03.png'
import cat04 from './images/pcat04.png'
import cat05 from './images/cat05.png'
import cat06 from './images/cat06.png'
import cat07 from './images/cat07.png'
import cat08 from './images/cat08.png'
import notice from './images/notice.png'
import mall01 from './images/mall01.jpg'
import mall02 from './images/mall02.jpg'
import mall03 from './images/mall03.jpg'
import ban01 from './images/ban01.png'
import ban02 from './images/ban02.png'
import searchimg from './images/search.png'



import foot03 from '../../assets/kedouimg01/foot07.png'
import foot04 from '../../assets/kedouimg01/foot4.png'
import foot05 from '../../assets/kedouimg01/foot09.png'

export default class Index extends Component {
  constructor(props) {
    super(props)
    this.state = {
      gglist:[],
      goodscat:[],
      goodslist:[],
      isid:'',
      navwidth:0,
      flindex:-1,
      znwns:'',
		  appmark:CommonJs.getmark(),
		  pageNumber:0,
		  hasNextPage:false,
		  scrollPd:false,
		  pageheight:0,
		  isIphoneX:0,
    }
  }
  config = {
    navigationBarTitleText: '加载中',
  }
  dobt(){
	if(this.state.appmark=='xjzb'){
		Taro.setNavigationBarTitle({title:'WUC商城'})
	}
	else{
		Taro.setNavigationBarTitle({title:'积分商城'})
	}
  }
  open(url, type) {
    if (Taro.getEnv() === Taro.ENV_TYPE.WEAPP) {
      this.$preload({
        type: type,
        malltype:'WUC'
      })
    } else if (Taro.getEnv() === Taro.ENV_TYPE.WEB) {
      url = url + '?type=' + type
    }

    CommonJs.openTo(url)
  }
  

  componentWillMount () {
	  this.dobt()
  	var par =this.$router.params
			var _this=this;
			if(par){
				var cs=par.scene;
				var vs=par.query_id;
				if(vs&&vs.indexOf('goodsxq')>=0){
					cs=vs
				}
				if(cs&&cs.indexOf('goodsxq')>=0){
					var arr=cs.split("goodsxq");
					var obj={};
					obj.qid=arr[0];
					var date1={ 
					  clusterId:arr[0]
					}
					CommonJs.ajaxRequest('/openClusterBindingUser/create',date1,'GET',function(res){},'noloading')
					if(arr.length>2){
						Taro.setStorage({key:'dateinfo',data:obj})
						Taro.setStorage({key:'shopId',data:arr[1]})
						Taro.setStorage({key:'goodsid',data:arr[2]+"|||WUC"})
						this.open('/pages/mall/goodsxq',arr[2])
					}
					else{
						Taro.setStorage({key:'dateinfo',data:obj})
						Taro.setStorage({key:'goodsid',data:arr[1]+"|||WUC"})
						if(arr[1]){
							var url='/mall/papi/v1.9/item/'+arr[1]
							
							CommonJs.ajaxRequest(url,'','GET',function(res){
								Taro.setStorage({key:'shopId',data:res.data.shop.shopId})
								_this.open('/pages/mall/goodsxq',arr[1])
							})
						}
					}
				}
				else if(cs&&cs.indexOf('goodstg')>=0){
					var arr=cs.split("goodstg");
					var obj={};
					obj.qid=arr[0];
					Taro.setStorage({key:'dateinfo',data:obj})
					Taro.setStorage({key:'goodsid',data:arr[1]})
					this.setsharcode(arr[1],arr[2])
					var url='/mall/papi/v1.9/item/'+arr[1]
					CommonJs.ajaxRequest(url,'','GET',function(res){
						Taro.setStorage({key:'shopId',data:res.data.shop.shopId})
						_this.open('/pages/mall/goodsxq',arr[1])
					})
				}
			}
  	
    this.getgg();
    this.getcat();
    this.getgoodslist(0);
    var navwidths = Taro.getStorageSync('navwidths')
    if (navwidths != '' || navwidths != 'undefined') {
      if (navwidths == 1) {
        Taro.getSystemInfo({
          success:function(res){
            var windowWidth = res.windowWidth
            var navwidth = windowWidth / 6
            _this.setState({
              navwidth:navwidth
            })
          }
        })
      }
    }
    const app = Taro.getApp();
  	let isIphoneX = app.globalData.isIphoneX;
  	
  	this.setState({
     	isIphoneX:isIphoneX
   })
  }


  componentDidMount() {}

  componentWillUnmount() {}

  componentDidShow() {}

  componentDidHide() {}
  getgg() {
    var shopId = Taro.getStorageSync('shopId')
    var url = '/advert/papi/v1.9/advert/type/5/' + shopId
    var _this = this
    CommonJs.ajaxRequest(url, '', 'GET', function(res) {
      var arr = res.data
      if (arr.length == 0) {
        var obj = {}
        obj.picUrl = ban02
        obj.targetType = 2
        arr[0] = obj
      }
      _this.setState({
        gglist: arr,
      })
    })
  }
  
  goodsxq(index) {
  	var goodsid=this.state.goodslist[index].id
  	Taro.setStorage({key:'goodsid',data:goodsid+"|||WUC"})
    this.open('/pages/mall/goodsxq', this.state.goodslist[index].id)
  }
  getcat(){
		var shopId = Taro.getStorageSync('shopId')
    var url='/commoditycredit/papi/v2.0/item-groups/'+shopId
    var _this=this;
    CommonJs.ajaxRequest(url,'','GET',function(res){
       _this.setState({
        goodscat: res.data
      })
    })
  }
  
  getGoodsByCatid(pageNumber,id){
	var url='/mallcredit/papi/v1.9/item?itemGroupId='+id+'&page='+pageNumber+'&activeStatus=ENABLE'
	var _this=this;
    CommonJs.ajaxRequest(url,'','GET',function(res){

		 if(res.data.page<res.data.totalPages){
			var hasNextPage = true
		 }
		 else{
			var hasNextPage = false
		 }
          var results = _this.state.goodslist
          var result = res.data.list;
          if(pageNumber==0){
          	results=[];
          }
          for(var i = 0; i < result.length; i++){
            results.push(result[i])
          }
          if (hasNextPage) {
            _this.setState({
              goodslist:results,
              pageNumber: res.data.page,
              hasNextPage: hasNextPage,
              scrollPd: true
            })
          }
		  else {
            _this.setState({
              goodslist:results,
              pageNumber: res.data.page,
              hasNextPage: hasNextPage,
              scrollPd: false
            })
          }

    })
  }
  loadMore(){
    var _this = this
    var pd = _this.state.scrollPd
    var isid = _this.state.isid
    if(pd) {
      //防止多次触发滑动到底部事件
      _this.setState({
        scrollPd: false//禁止下拉
      })
      var pageNumber = _this.state.pageNumber + 1
      if(isid){
        _this.getGoodsByCatid(pageNumber,isid)
      }else{
        _this.getgoodslist(pageNumber)
      }
      
    }else{
      var hasNextPage =  _this.state.hasNextPage
      if(hasNextPage){
        Taro.showToast({
          title:'正在加载数据...',
          icon: 'none',
          duration: 2000
        })
      }else{
        Taro.showToast({
          title:'没有更多数据啦！',
          icon: 'none',
          duration: 2000
        })
      }
    }
  }
  choosefl(index){

   	if(index==-1){
   		 this.setState({
	      flindex:index,
	      goodslist:[]
	      })
   		this.getgoodslist(0)
      
    }
   	else{
   		 this.setState({
	      flindex:index,
	      isid:this.state.goodscat[index].id,
	      goodslist:[]
      })
   		this.getGoodsByCatid(0,this.state.goodscat[index].id)
      
     }
  }
  getgoodslist(pageNumber) {
    var url ='/mallcredit/papi/v1.9/item?activeStatus=ENABLE&shopId='+Taro.getStorageSync('shopId')
    var _this = this
    var dates={
      size:10,
      page:pageNumber
    }
    CommonJs.ajaxRequest(url, dates, 'GET', function(res) {
      if (res) {

        if(res.data.totalPages>pageNumber){
          var hasNextPage = true;
        }
        else{
          var hasNextPage = false;
        }
        var result = res.data.list
        
        if(pageNumber == 0){
          results = result
        }
        else{
        	var results = _this.state.goodslist
	        for(var i = 0; i < result.length; i++){
	          results.push(result[i]);
	        }
	      }
        if (hasNextPage) {
          _this.setState({
            goodslist: results,
            znwns: '暂无数据',
            pageNumber: res.data.page,
            hasNextPage: hasNextPage,
            scrollPd: true
          })
        }
        else {
          _this.setState({
            goodslist: results,
            znwns: '暂无数据',
            pageNumber: res.data.page,
            hasNextPage: hasNextPage,
            scrollPd: false
          })
        }
      } 
    },'wfw')
  }
  goopen(type,url){
	  this.$preload({
	    malltype:type
	  })
    CommonJs.openTo(url)
  }
  render() {
    const gglist = this.state.gglist
    const goodslist = this.state.goodslist
    const goodscat= this.state.goodscat;
    const appmark= this.state.appmark;
    return (
      <View className='page'>
      
				<View className='focusImg'>
					<Swiper
					className="swiper-container"
					autoplay>
	         {gglist.map((item, index) => (
					 <SwiperItem onClick={this.gggoto.bind(this,item.targetType,item.targetId)}>
					   <Image className="swiper-img" mode="widthFix" src={item.picUrl}></Image>
					 </SwiperItem>
	         ))}
				  </Swiper>
				</View>
				<View className='tj-goods'>
					<View className='tit catfl' style="background-color:#fff">
						<ScrollView 
	              className='qun-fung' 
	              scrollX='true'
	              scrollLeft={this.state.navwidth}>
									<Text className={-1==this.state.flindex?'tit01 tit02':'tit01'} onClick={this.choosefl.bind(this,-1)}>全部</Text>
									{goodscat.length>0&&goodscat.map((item, index) => (
										<Text className={index==this.state.flindex?'tit01 tit02':'tit01'} onClick={this.choosefl.bind(this,index)}>{item.groupName}</Text>
									))}
						</ScrollView>
					</View>
				</View>

        <ScrollView className='qun-mingxibo' scrollY='true' style="background-color:#f1f1f1" onScrollToLower={this.loadMore.bind(this,'')}>
				<View className='goodslist' style={appmark=='xjzb'?'margin-top:0;padding-bottom:170rpx':'display:none;margin-top:0;'}>
					<View className='nodate' style={!goodslist||goodslist.length==0?'':'display:none'}>该分类暂无WUC商品</View>
					{goodslist.map((item, index) => (
					<View className='goods-li' onClick={this.goodsxq.bind(this,index)}>
						<View className='goods-img'>
							<Image className='img' mode='widthFix' src={item.logoUrl?item.logoUrl:CommonJs.getlogo}></Image>
						</View>
						<View className='goods-text'>{item.name}</View>
						<View className='goods-pri'>
							<Text className='goods-bz'>WUC</Text>
							<Text className='goods-jg'>{item.price.specialPrice/100}</Text>
							<Text className='goods-sy'>剩余：{item.saleStock.stockAmount}件</Text>
						</View>
					</View>
					))}
				</View>

        <View className='goodslist' style={appmark=='xjzb'?'display:none;margin-top:0;':'margin-top:0;padding-bottom:170rpx'}>
					<View className='nodate' style={!goodslist||goodslist.length==0?'':'display:none'}>该分类暂无积分商品</View>
					{goodslist.map((item, index) => (
					<View className='goods-li' onClick={this.goodsxq.bind(this,index)}>
						<View className='goods-img'>
							<Image className='img' mode='widthFix' src={item.logoUrl?item.logoUrl:CommonJs.getlogo}></Image>
						</View>
						<View className='goods-text'>{item.name}</View>
						<View className='goods-pri'>
							<Text className='goods-bz'>积分</Text>
							<Text className='goods-jg'>{item.price.specialPrice/100}</Text>
							<Text className='goods-sy'>剩余：{item.saleStock.stockAmount}件</Text>
						</View>
					</View>
					))}
				</View>
        </ScrollView>
         <View className='footer' style={this.state.isIphoneX==1?'padding-bottom:58rpx;display:flex;':'display:flex;'}>
					<View className='footer-dl' onClick={this.goopen.bind(this,'WUC','/pages/mall/shopcar')}>
						<View className='footer-dt'>
							<Image className='footer-img' mode='widthFix' src={foot04}></Image>
						</View>
						<View className='footer-dd'>购物车</View>
					</View>
					<View className='footer-dl' onClick={this.goopen.bind(this,'WUC','/pages/my/unpaid')}>
						<View className='footer-dt'>
							<Image className='footer-img' mode='widthFix' src={foot03}></Image>
						</View>
						<View className='footer-dd'>订单</View>
					</View>
					<View className='footer-dl' onClick={this.goopen.bind(this,'WUC','/pages/my/my')}>
						<View className='footer-dt'>
							<Image className='footer-img' mode='widthFix' src={foot05}></Image>
						</View>
						<View className='footer-dd'>我的</View>
					</View>
				</View>
			</View>

    )
  }
}
